import { parseTime } from '@/utils'
import { types } from './constant'

export function treeIconClass(data) {
  const icon = {
    0: 'profile',
    1: 'sub-profile',
    2: 'label-object',
    3: 'label-value'
  }
  return icon[data.tableType || 0]
}

export function mapLayoutData(item, referenceTables) {
  let table
  if (item.valueType === 5 && referenceTables) {
    const refTable = referenceTables.find(
      (table) => table.id === item.refTableSchemaId
    )
    if (refTable) {
      table = {
        id: item.refTableSchemaId,
        tableType: refTable.tableType
      }
    }
  }
  return {
    ...item,
    i: item.paramLayoutId,
    title: item.title,
    valueType: item.valueType,
    type: item.type,
    w: item.w,
    y: item.y,
    x: item.x,
    h: item.h,
    label: item.label,
    table: table,
    edit: false,
    defaultValues:
      item.valueType === types.REFERENCE
        ? item.defaultValues.map((item) => (item ? item.name : ''))
        : item.defaultValues && item.defaultValues.length === 1
          ? item.defaultValues[0]
          : ''
  }
}

// 从头像库中找到用户对应的头像
export function avatar(avatars, logoUrl) {
  const avatar = avatars.find((avatar) => avatar.name === logoUrl)
  return avatar ? avatar.src : require('@/assets/images/head-logo/1.png')
}

// 日期格式的参数保存前做格式化，从date类型转成字符串类型。最后的结果是 yyyy/mm/dd 类似这种格式的字符串
export function formatDateParameter(parameter, name) {
  const formatter = parameter.formatter.replace(
    /([ymdMHs])+/g,
    (result, key) => {
      const value = key === 'm' ? 'i' : key
      return '{' + value.toLowerCase() + '}'
    }
  )

  const dateValue = parseTime(parameter[name], formatter)

  return dateValue
}

// 将字符串转为日期类型，在设计界面更改日期格式的时候需要用到
export function parseDate(time, format) {
  let _formats = []
  let _times = []
  const _value = {}
  const re = /\s|\/|\-|\:/
  _times = time.split(re)
  _formats = format.split(re)
  _formats.forEach((key, idx) => {
    if (key === 'MM') {
      _value[key] = String(Number(_times[idx]) - 1).padStart(2, 0)
    } else {
      _value[key] = _times[idx]
    }
  })

  if (format.includes('HH')) {
    return new Date(_value.yyyy, _value.MM, _value.dd, _value.HH, _value.mm, _value.ss)
  } else {
    return new Date(_value.yyyy, _value.MM, _value.dd)
  }
}
